/*
@Time : 2022/9/14 17:22
@Author : gaozhichang
@File : goroutine_map.go
@des: goroutine 并发读写map会报错
*/
package main

import (
	"fmt"
	"sync"
)

/*
	如果定义全局的map会报错，应为golang map不支持并发读写。会 panic
	方案1： 改成函数内变量
	方案2： map读写加锁
*/
var CompanyList map[int]string
var myLock sync.RWMutex

func main() {
	wg := &sync.WaitGroup{}
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func(wg *sync.WaitGroup) {
			res := GetCompanyInfoByShopId(14780)
			fmt.Println(fmt.Sprintf("--->%s", res))
			wg.Done()
		}(wg)
	}
	wg.Wait()
	fmt.Println("--------------------------------")
}

func GetCompanyInfoByShopId(shopid int) string {
	//解决方案2
	myLock.Lock()
	defer myLock.Unlock()
	//解决方案2

	//解决方案1 CompanyList := make(map[int]string)
	CompanyList = make(map[int]string)

	CompanyList[14780] = "欢迎来到1"
	CompanyList[15925] = "欢迎来百2"
	CompanyList[15926] = "欢迎来五3"
	CompanyList[19148] = "欢迎来五4"
	CompanyList[20068] = "欢迎来五5"
	CompanyList[21215] = "欢迎来五6"

	if _, ok := CompanyList[shopid]; ok {
		return CompanyList[shopid]
	}
	return ""
}
